<template>
  <div class="">
    <el-form :inline="true">
      <div style="display: flex; justify-content: space-between;">
        <div>
          <el-form-item>
            <el-input v-model="key" clearable placeholder="请输入账号" style="width: 200px;" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="ordercode" clearable placeholder="请输入订单号" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="店铺：">
            <el-select v-model="selleruserid" filterable remote placeholder="请输入" :remote-method="getShopList"
              :loading="shopLoading">
              <el-option :key="-1" label="全部" :value="0"></el-option>
              <el-option v-for="item in shopList" :key="item.userid" :label="item.shopname" :value="item.userid">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="state" placeholder="状态">
              <!-- <el-option label="全部" :value="0" />
              <el-option label="待支付" :value="1" />
              <el-option label="待发货" :value="2" />
              <el-option label="待签收" :value="3" />
              <el-option label="已签收" :value="4" />
              <el-option label="已关闭" :value="5" />
              <el-option label="售后中" :value="6" /> -->
              <el-option v-for="item in Object.keys(OrderStateList)" :label="OrderStateList[item]"
                :value="Number(item)" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="dateTime" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
              start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getData">查询</el-button>
          </el-form-item>
        </div>
        <!-- <div>
          <el-button type="primary" :loading="exportLoading" @click="doExport">导出Excel</el-button>
        </div> -->
        <div>
          <download-excel class="export-excel-wrapper" :data="excelpage" :fields="json_fields" :name="fileName">
            <el-button type="primary">导出Excel</el-button>
          </download-excel>
        </div>
      </div>
    </el-form>
    <!-- 列表信息 -->
    <el-table v-loading="listLoading" :data="tableData" border style="width: 100%">
      <el-table-column prop="orderCode" show-overflow-tooltip label="订单编号" width="180" align="center" />
      <el-table-column prop="username" show-overflow-tooltip label="购买账号" align="center" width="120" />
      <el-table-column prop="picurl" label="商品图" width="80" align="center">
        <template slot-scope="{row}">
          <el-image style="width: 50px; height: 50px" :src="row.picurl.split(',')[0]"
            :preview-src-list="row.picurl.split(',')" />
        </template>
      </el-table-column>
      <el-table-column prop="shopname" show-overflow-tooltip label="店铺名称" align="center" />
      <el-table-column prop="gname" show-overflow-tooltip label="商品名称" align="center" />
      <el-table-column prop="totalAmount" label="商品金额" width="100" align="center">
        <template slot-scope="scope">
          <div>
            <span>￥{{ scope.row.totalAmount }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="buyCount" label="购买数量" width="80" align="center" />
      <el-table-column prop="yf" label="运费" width="70" align="center">
        <template slot-scope="scope">
          <div>
            <span>￥{{ scope.row.yf }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="paycoin" label="支付类型" width="110" align="center">
        <template slot-scope="{row}">
          <span>{{ PayTypeList[row.paycoin] || '余额' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="feecoinid" label="消耗积分" align="center">
        <template slot-scope="{row}">
          <div>币种：{{ coinList[row.feecoinid] || '' }}</div>
          <div>数量：{{ row.feejf }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" align="center" width="100">
        <template slot-scope="{row}">
          <el-tag type="danger" v-if="row.state == 1">{{ OrderStateList[row.state] }}</el-tag>
          <el-tag v-if="row.state == 2">{{ OrderStateList[row.state] }}</el-tag>
          <el-tag type="warning" v-if="row.state == 3">{{ OrderStateList[row.state] }}</el-tag>
          <el-tag type="info" v-if="row.state == 4">{{ OrderStateList[row.state] }}</el-tag>
          <el-tag type="info" v-if="row.state == 5">{{ OrderStateList[row.state] }}</el-tag>
          <el-tag type="warning" v-if="row.state == 6">{{ OrderStateList[row.state] }}</el-tag>
          <el-tag type="info" v-if="row.state == 7">{{ OrderStateList[row.state] }}</el-tag>
          <el-tag v-if="row.state == 8">{{ OrderStateList[row.state] }}</el-tag>
          <el-tag type="danger" v-if="row.state == 9">{{ OrderStateList[row.state] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流信息" width="100" align="center">
        <template slot-scope="scope">
          <el-popover placement="top-start" width="300" trigger="click"
            v-if="scope.row.state == 2 || scope.row.state == 3 || scope.row.state == 4">
            <div>
              <p>收货人：{{ scope.row.username }}</p>
              <p>联系方式：{{ scope.row.exp_phone }}</p>
              <p>收货地址：{{ scope.row.exp_address }}</p>
              <p v-if="scope.row.state > 1">支付时间：{{ scope.row.paytime.replace("T", " ") }}</p>
              <p v-if="scope.row.exp_code">物流单号：{{ scope.row.exp_code }}</p>
              <p v-if="scope.row.exp_code">发货时间：{{ scope.row.sendtime.replace("T", " ") }}</p>
              <p v-if="scope.row.state > 3">确认收货时间：{{ scope.row.dealtime.replace("T", " ") }}</p>
            </div>
            <div slot="reference" style="cursor:pointer">点击查看</div>
          </el-popover>
          <div v-else>暂无</div>
        </template>
      </el-table-column>
      <el-table-column prop="ctime" show-overflow-tooltip label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.ctime.replace("T", " ") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160px" align="center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.state == 2" size="mini" type="primary"
            @click="shipmentsVisibleFn(scope.row)">发货</el-button>
          <el-button v-if="scope.row.state == 3" size="mini" type="primary"
            @click="openUrl(scope.row.exp_code)">查看物流</el-button>
          <el-button v-if="scope.row.state == 6" size="mini" type="primary" @click="Artersell(scope.row)">售后处理</el-button>
          <el-button v-if="scope.row.state == 8 || scope.row.state == 9 || scope.row.state == 6" size="mini"
            type="primary" @click="AftersellList(scope.row.id)">售后处理记录</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block " style="padding-top: 20px;">
      <el-pagination background :current-page="PageIndex" :page-sizes="[10, 20, 30, 40]" :page-size="PageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="totalCount" @size-change="idx => { PageSize = idx }"
        @current-change="idx => { PageIndex = idx }" />
    </div>

    <!-- 发货 -->
    <el-dialog width="500px" :close-on-click-modal="false" title="发货" :visible.sync="shipmentsVisible">
      <el-form id="forms" ref="forms" :rules="rulesModel" :model="shipmentsForm" label-width="100px">
        <!-- <el-form-item label="快递公司" prop="comcode">
          <el-input v-model="shipmentsForm.comcode" placeholder="请填写快递公司" />
        </el-form-item> -->
        <el-form-item label="快递单号" prop="kdcode">
          <el-input v-model="shipmentsForm.kdcode" placeholder="请填写快递单号" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="shipmentsVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="shipments()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 处理售后 -->
    <el-dialog width="500px" :close-on-click-modal="false" title="售后处理" :visible.sync="AftersellVisible"
      @closed="closedDialog">
      <el-form id="form" ref="form" :rules="rulesArtersell" :model="ArtersellForm" label-width="100px">
        <el-form-item label="售后处理" prop="state">
          <el-radio-group v-model="ArtersellForm.state">
            <el-radio :label="8">通过</el-radio>
            <el-radio :label="9">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="ArtersellForm.state == 8" label="退款金额" prop="amount">
          <el-input v-model="ArtersellForm.amount" type="number" placeholder="请输入退款金额" />
          <div>注意：退款到现金余额</div>
        </el-form-item>
        <el-form-item v-if="ArtersellForm.state == 9" label="驳回理由" prop="content">
          <el-input v-model="ArtersellForm.content" placeholder="请输入驳回理由" />
        </el-form-item>
        <div>
          <el-form-item label="图片说明">
            <UploadImageList :isImageList="false" :existImage="ArtersellForm.picurl"
              @success="val => ArtersellForm.picurl = val" :isDisplay="AftersellVisible" />
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AftersellVisible = false">取 消</el-button>
        <el-button :loading="Aftersellloading" type="primary" @click="ArtersellSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 售后处理列表 -->
    <el-dialog width="1000px" :close-on-click-modal="false" title="售后处理记录" :visible.sync="AftersellListVisible">
      <el-table :data="aftersellList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column prop="picurl" label="图片" width="100" align="center">
          <template slot-scope="{row}">
            <el-image style="width: 60px; height: 60px" :src="row.picurl.split(',')[0]"
              :preview-src-list="row.picurl.split(',')" />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" align="center" />
        <el-table-column prop="ctime" label="创建时间" align="center">
          <template slot-scope="{row}">
            <span>{{ row.ctime.replace("T", " ") }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { getorderpage, SetExpCode, order_excel, AftersellOrder, AftersellList } from "@/api/order.js";
import { GetEnum } from "@/api/ctrls.js";
import { getEnumList } from '@/utils/auth.js'
import { formatDate } from "@/utils/index.js";
import { number } from "echarts/lib/export";
import { MallShopPage } from "@/api/goods.js";
export default {
  name: "Name",
  data() {
    return {
      exportLoading: false,
      loading: false,
      key: "", // 关键词
      selleruserid: 0,
      ordercode: "", // 订单号搜索
      state: 0, // 订单状态
      dateTime: "", // 时间查询
      types: "-1",
      typeList: [],
      listLoading: false,
      tableData: [],
      totalCount: 0,
      PageIndex: 1,
      PageSize: 10,
      dialogVisible: false,
      shipmentsVisible: false, // 发货弹窗
      shipmentsForm: {}, // 发货信息
      rulesModel: {
        kdcode: [{ required: true, message: "请填写快递单号", trigger: "blur" }]
      },
      PayTypeList: {},// 支付方式列表
      coinList: {}, // 币种列表
      OrderStateList: {}, // 订单状态
      excelpage: [], // 存放用于导出excel的数据
      json_fields: {
        订单编号: {
          field: "orderCode",
          callback: value => {
            return "&nbsp;" + value;
          }
        },
        支付用户: "username", //支持嵌套属性
        订单金额: "totalAmount",
        商品名称: "gname",
        购买数量: "buyCount",
        消耗币种: {
          field: "feecoinid",
          callback: value => {
            return this.coinList[value];
          }
        },
        消耗数量: "feejf",
        收货人: "exp_username",
        收货人手机: "exp_phone",
        收货地址: "exp_address",
        订单时间: {
          field: "ctime",
          callback: value => {
            return value.replace("T", " ");
          }
        }
      },
      json_meta: [
        [
          {
            key: "charset",
            value: "utf-8"
          }
        ]
      ],
      fileName: '订单列表',

      // 售后处理
      AftersellVisible: false,
      Aftersellloading: false,
      ArtersellForm: {},
      rulesArtersell: {
        state: [{ required: true, message: "请选择处理状态", trigger: "blur" }],
        amount: [{ required: true, message: "请输入退款金额", trigger: "blur" }],
        content: [{ required: true, message: "请输入驳回说明", trigger: "blur" }],
      },

      // 售后处理记录
      AftersellListVisible: false,
      aftersellList: [],

      // 店铺
      shopList: [], // 店铺列表
      shopKey: '',
      shopLoading: false,
    };
  },
  computed: {
    // fileName(){
    //   return this.dateTime[0] + "-" + this.dateTime[1] + "订单列表.xlsx"
    // }
  },
  watch: {
    PageIndex(val) {
      console.log(val);
      this.getData();
    }
  },
  created() {
    // const time = parseInt(Date.now() / 1000);
    // this.dateTime[0] = formatDate(
    //   new Date((time - 10 * 24 * 60 * 60) * 1000),
    //   "yyyy-MM-dd"
    // );
    // this.dateTime[1] = formatDate(new Date(), "yyyy-MM-dd");
  },
  mounted() {
    this.getData();
    this.GetEnum();
    // 获取店铺列表
    this.getShopList();
  },
  methods: {
    // 获取枚举
    async GetEnum() {
      const res = await GetEnum();
      this.PayTypeList = res.data['PayType'];
      this.coinList = res.data['Coin'];
      this.OrderStateList = res.data['OrderState'];
    },
    openUrl(code) {
      window.open(`https://m.kuaidi100.com/result.jsp?nu=${code}`, "_blank");
    },
    // 导出报表
    async doExport() {
      this.exportLoading = true;
      const res = await order_excel({
        key: this.key,
        state: this.state,
        stime: this.dateTime ? this.dateTime[0] : "",
        etime: this.dateTime ? this.dateTime[1] : ""
      });
      this.exportLoading = false;
      if (res) {
        //转换数据类型
        const xlsx = "application/vnd.ms-excel;charset=utf-8";
        const blob = new Blob([res], { type: xlsx });
        // 转换完成，创建一个a标签用于下载
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = URL.createObjectURL(blob);
        const fileName = this.dateTime[0]
          ? this.dateTime[0] + "-" + this.dateTime[1] + "订单列表.xlsx"
          : "订单列表.xlsx";
        a.setAttribute("download", fileName);
        document.body.appendChild(a);
        a.click();
        a.remove();
        // document.body.removeChild(a);
      }
    },
    shipmentsVisibleFn(item) {
      this.shipmentsForm = {
        comcode: "",
        kdcode: "",
        ...item
      };
      this.shipmentsVisible = true;
    },
    /////////////////////////////////////////////////  售后处理 //////////////////////////////////////
    /**售后处理按钮点击 */
    Artersell(item) {
      this.ArtersellForm = {
        orderid: item.id,
        state: 9, // 处理状态
        amount: 0, // 退款金额
        content: '', // 驳回说明
        picurl: '', // 图片说明
      }

      this.AftersellVisible = true;
    },
    /**售后处理提交 */
    async ArtersellSubmit() {
      try {
        await this.$refs['form'].validate()
      } catch (e) {
        console.log(e)
        return
      }
      this.Aftersellloading = true;
      const { success, msg } = await AftersellOrder(this.ArtersellForm);
      this.Aftersellloading = false;
      if (success) {
        this.getData();
        this.AftersellVisible = false;
      }
      this.$message({
        message: msg,
        type: success ? "success" : "error"
      });

    },
    /**对话框关闭前（售后处理） */
    closedDialog() {
      // 移除表单项的校验结果
      this.$refs.form.clearValidate();
    },
    /**售后处理列表 */
    async AftersellList(orderid) {
      this.aftersellList = [];
      const { success, msg, data } = await AftersellList({
        orderid
      });
      if (success) {
        this.aftersellList = data;
        this.AftersellListVisible = true;
      } else {
        this.$message({
          message: msg,
          type: success ? "success" : "error"
        });
      }
    },
    /**发货 */
    async shipments() {
      try {
        await this.$refs['forms'].validate()
      } catch (e) {
        console.log(e)
        return
      }
      const { success, msg } = await SetExpCode({
        //  comcode: this.shipmentsForm.comcode,
        id: this.shipmentsForm.id,
        expcode: this.shipmentsForm.kdcode
      });
      this.getData();
      if (success) {
        this.shipmentsVisible = false;
      }
      this.$message({
        message: msg,
        type: success ? "success" : "error"
      });
    },
    async getData() {
      this.listLoading = true;
      const { list, pageIndex, totalCount } = await getorderpage({
        key: this.key,
        state: this.state,
        ordercode: this.ordercode,
        selleruserid: Number(this.selleruserid) || 0,
        stime: this.dateTime ? this.dateTime[0] : "",
        etime: this.dateTime ? this.dateTime[1] : "",
        PageIndex: this.PageIndex,
        PageSize: this.PageSize
      });
      this.totalCount = totalCount;
      this.tableData = list;
      this.excelpage = list;
      this.listLoading = false;
    },
    /**获取店铺列表 */
    async getShopList(val) {
      this.shopLoading = true;
      const { list, totalCount, success, msg } = await MallShopPage({
        key: val || '',
        PageIndex: 1,
        PageSize: 100
      })
      this.shopLoading = false;
      this.shopList = list
      // console.log('店铺列表，', list)
    },
  }
};
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.el-table .warning-row {
  background: oldlace;
}

// 上传图片相关样式
.avatar-uploader .el-upload {
  width: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
</style>
